import privateSeaInterface from "/api/privateSea/privateSeaInterface";
import request from "/utils/request";
import omsRequest from "/utils/omsRequest";
import { showToast } from "/utils/common";
import { validtatePhone } from "/utils/commonMethod";
const Promise = require("/plugins/es6-promise");

const app = getApp();
Page({
  data: {
    form: {
      // form表单提交参数
      shopList: [], // 该商户下对应的分店list表
      contacts: "", // 商户联系人
      contactNumber: "", //kp联系电话
      remark: "", // 备注
    },
    selectStoreNumber: 0,
    selectAll: false, // 全选
    floorNumber: 1, //更多门店信息-楼层数
    stepsNumber: 3, //---展示3条信息-阶梯数
  },
  onLoad(option) {
    this.getShopInfo(option.shopId, option.dpid)
      .then()
      .catch((err) => {
        dd.hideLoading();
        if (err === "notify" || err === "406") return;
        dd.confirm({
          title: "门店解析失败",
          content: "重新解析？",
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          success: function (res) {
            if (res.confirm) {
              dd.redirectTo({
                url:
                  "/pages/privateCustomers/resovle-store-link/resovle-store-link",
              });
            }
          },
        });
      });
  },
  getShopInfo(shopId, dpid) {
    return new Promise((resolve, reject) => {
      dd.showLoading({
        content: "门店数据过多请稍后...",
      });
      let { brand, model, system, platform } = app.globalData.systemInfo;
      let { useAgent } = app.globalData.userInfo;
      let agent;
      if (platform === "iOS") {
        agent = `MApi 1.4 (dpscope 10.37.3 appstore; ${brand} ${
          system.match(/\d+\.\d+/)[0]
          } ${model}; a0d0)`;
      } else if (platform === "Android") {
        let length = system.split(".").length;
        switch (length) {
          case 1:
            system += ".0.0";
            break;
          case 2:
            system += ".0";
            break;
        }
        agent = `MApi 1.4 (com.dianping.v1 10.38.4 om_sd_yybsc ${model}; Android ${system})`;
      }

      let _headers = useAgent ? { ...useAgent } : {
          "Accept-Encoding": "identity",
          "User-Agent": agent,
          "picasso": "no-js",
          "pragma-os": agent,
          "pragma-dpid": dpid,
          "Host": "mapi.dianping.com",
        }
      // 之前的逻辑
      dd.downloadFile({
        url: `https://mapi.dianping.com/mapi/shop.bin?${/^\d+$/.test(shopId) ? `shopid=${shopId}` : `shopuuid=${shopId}`}`,
        method: "GET",
        headers: _headers,
        success: (response) => {
          dd.uploadFile({
            url: `${app.globalData.omsDomain}/ding/decryptDpApp`,
            fileType: 'image',
            fileName: 'file',
            filePath: response.filePath,
            success: (res) => {
              res.data = JSON.parse(res.data)
              console.log(res.data)
              if (res.data.success) {
                if (res.data.vo && res.data.vo.customData) {
                  // let requestCode = res.data.vo.customData.requestCode;
                  let verifyPageUrl = res.data.vo.customData.verifyPageUrl
                  //去滑块验证
                  // var url = `/pages/privateCustomers/verfify/verfify?verifyPageUrl=${verifyPageUrl}&userAgent=${
                  //   encodeURIComponent(useAgent ? useAgent["User-Agent"] : agent)
                  //   }&shopId=${shopId}&dpid=${dpid}`;
                  // console.log(url,'编号后的url')

                  let newUrl = `/pages/privateCustomers/verfify/verfify?verifyPageUrl=${encodeURIComponent(verifyPageUrl)}`
                  console.log(newUrl,"newUrl")
                  dd.redirectTo({
                    // url: url.replace("(", "LeftKuoHao").replace(")", "RightKuoHao"),
                    url: newUrl
                  });
                  reject("406")
                } else if (res.data.vo) {
                  //.bin接口去获取分门店列表
                  //如果.bin 接口出现406 或者其他异常， 同理处理
                  // 解析shopId&shopUuid
                  let paramsArr = decodeURIComponent(res.data.vo.shopServeInfoUrl).split('?').pop().split('&')
                  let params = {}
                  params = paramsArr.reduce((obj, cur) => {
                    let arr = cur.split('=')
                    obj[arr[0]] = arr[1]
                    return obj
                  }, params)
                  Object.assign(res.data.vo, {
                    id: +params.shopId,
                    shopId: + params.shopId,
                    shopUuid: params.shopuuid,
                    selectedFlag: true
                  })
                  // 分店数据
                  if (res.data.vo.branchIds) {
                    if (res.data.vo.branchIds.split(',').length <= 50) {
                      omsRequest({
                        url: '/ding/getShopBranches',
                        data: {
                          shopId: res.data.vo.shopId,
                          lng: res.data.vo.lng,
                          lat: res.data.vo.lat
                        }
                      }).then(result => {
                        if (result.success) {
                          result.voList.map(item => {
                            item.shopId = item.id
                            item.selectedFlag = true
                          })
                          this.setData({
                            "form.shopList": [res.data.vo, ...result.voList],
                            selectAll: true
                          });
                          this.computedSelectStoreNumber()
                          dd.hideLoading()
                          resolve()
                        } else {
                          reject()
                        }
                      }).catch(err => {
                        reject(err)
                      })
                    } else {
                      dd.hideLoading()
                      dd.alert({
                        content: "暂不支持超过50家分店的门店，请联系技术",
                        success: () => {
                          reject()
                        }
                      })
                    }
                  } else {
                    this.setData({
                      "form.shopList": [res.data.vo],
                      selectAll: true
                    });
                    this.computedSelectStoreNumber()
                    dd.hideLoading()
                    resolve()
                  }
                } else {
                  const errInfo = '点评接口问题，请稍后重试'
                  this.requestSendNotify({ useAgent, agent, dpid, shopId, errInfo })
                  dd.alert({
                    content: errInfo,
                    success: () => {
                    }
                  })
                  reject('notify')
                }
              } else {
                const errInfo = res.data.messages[0];
                this.requestSendNotify({ useAgent, agent, dpid, shopId, errInfo })
                dd.alert({
                  content: errInfo,
                  success: () => {
                  }
                })
                reject('notify')
              }
            },
            fail: function (err) {
              reject(err)
            }
          });
        },
        fail: function (err) {
          reject(err)
        }
      })
    });
  },
  requestSendNotify({ useAgent, agent, dpid, shopId, err }) {
    request({
      url: privateSeaInterface.sendNotify,
      method: "post",
      headers: {
        "Content-Type": "application/json",
      },
      data: {
        userAgent: useAgent ? useAgent["User-Agent"] : agent,
        dpid,
        requestData: shopId,
        responseData: JSON.stringify(err),
        deviceInfo: app.globalData.systemInfo,
      },
    }).then((res) => {
      if (res.success) {
        dd.redirectTo({
          url: "/pages/privateCustomers/resovle-store-link/resovle-store-link",
        });
      }
    });
  },
  loadMore() {
    this.setData({
      floorNumber: 99,
    });
  },
  fold() {
    this.setData({
      floorNumber: 1,
    });
  },
  // 全选
  allCheckChange(e) {
    //
    this.data.form.shopList.forEach((item) => {
      item.selectedFlag = e.detail.value;
    });
    this.setData({
      selectAll: e.detail.value,
      "form.shopList": this.data.form.shopList,
    });
    this.computedSelectStoreNumber();
  },
  // 门店是否勾选分店
  checkedValChange(e) {
    let index = e.currentTarget.dataset.index; // 当前操作的对象在数组中索引
    this.data.form.shopList[index].selectedFlag = e.detail.value;
    this.setData({
      "form.shopList": this.data.form.shopList, //更新视图
      selectAll: this.data.form.shopList.some(
        (item) => item.selectedFlag === true
      ), // 反选
    });
    this.computedSelectStoreNumber();
  },
  // 计算当前选中分家店数
  computedSelectStoreNumber() {
    this.setData({
      selectStoreNumber: this.data.form.shopList.filter(
        (item) => item.selectedFlag === true
      ).length,
    });
  },
  onReset() { },
  onSubmit(e) {
    Object.assign(this.data.form, e.detail.value);
    //0 -校验
    //所选门店至少为一个
    if (this.data.form.shopList.every((item) => item.selectedFlag == false)) {
      showToast({
        msg: "所选门店至少为一个",
      });
      return;
    }
    //手机号校验
    if (
      this.data.form.contactNumber &&
      !validtatePhone(this.data.form.contactNumber)
    ) {
      return;
    }
    // 处理点评接口403  门店名称不存在情况
    if (this.data.form.shopList.some((item) => !item.name)) {
      dd.alert({
        content: "点评数据异常",
      });
      // dd.confirm({
      //   title: '数据异常',
      //   content: '是否手动添加私海数据？',
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消',
      //   success: function (res) {
      //     if (res.confirm) {
      //       dd.redirectTo({
      //         url: "/pages/privateCustomers/custom-add-private/custom-add-private"
      //       })
      //     }
      //   }
      // })
      return;
    }
    dd.showLoading({
      content: "加载中...",
    });
    // 处理 添加成功也所需所选门店
    let allShopNum = this.data.form.shopList.length;
    let selectedShopNum = this.data.form.shopList.filter(
      (item) => item.selectedFlag == true
    ).length;
    request({
      url: privateSeaInterface.createPrivateSeaShop,
      method: "post",
      headers: {
        "Content-Type": "application/json",
      },
      data: this.data.form,
    }).then((res) => {
      if (res.success) {
        dd.hideLoading();
        dd.redirectTo({
          url: `/pages/privateCustomers/add-private-sea-success/add-private-sea-success?selectedShopNum=${selectedShopNum}&allShopNum=${allShopNum}`,
        });
      } else {
        dd.hideLoading({
          success: function () {
            dd.alert({
              content: res.messages[0],
            });
          },
        });
      }
    });
  },
});
